package mianyang.zhangsan.com.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;

public class ExcelUtils {

    public static void exportExcel(String title, String[] headers, Collection<String[]> contents, OutputStream out){
        //声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认的列宽为15字节
        sheet.setDefaultColumnWidth((short)15);
        //设置标题行样式
        HSSFCellStyle headerSytle = workbook.createCellStyle();
        //生成字体
        HSSFFont headerFont = workbook.createFont();
        headerFont.setFontName("宋体");
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerSytle.setFont(headerFont);
        //设置内容样式
        HSSFCellStyle contentStyle = workbook.createCellStyle();
        //生成字体
        HSSFFont contentFont = workbook.createFont();
        headerFont.setFontName("宋体");
        headerFont.setFontHeightInPoints((short) 10);
        contentStyle.setFont(contentFont);
        //添加标题行
        HSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++){
            HSSFCell cell = headerRow.createCell(i);
            cell.setCellStyle(headerSytle);
            cell.setCellValue(headers[i]);
        }
        //添加内容
        Iterator<String[]> iterator = contents.iterator();
        int index = 0;
        while(iterator.hasNext()){
            index++;
            HSSFRow contentRow = sheet.createRow(index);
            String[] content = iterator.next();
            for(int i = 0; i < content.length; i++){
                HSSFCell contentCell = contentRow.createCell(i);
                contentCell.setCellStyle(contentStyle);
                String textValue = content[i];
                contentCell.setCellValue(textValue);
            }
        }

        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
